package com.wuyou.filter;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.wuyou.domain.Result;
import com.wuyou.em.ResultEnum;
import com.wuyou.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.RequestPath;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Set;

@Component
public class TokenFilter implements GlobalFilter, Ordered {

    @Autowired
    private JwtUtil jwtUtil;

    @Value("#{'${gateway.excludes.url}'.empty?null : '${gateway.excludes.url}'.split(',')}")
    private Set<String> excludeUrl;//需要排除的路径

    //请求路径对比工具
    private PathMatcher pathMatcher = new AntPathMatcher();
    //过滤器方法
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        //获取request对象
        ServerHttpRequest request = exchange.getRequest();

        //当前请求的路径
        String path = request.getURI().getPath();

        for (String url : excludeUrl) {
            //参数: 路径的格式 , 匹配的路径
            if(pathMatcher.match(url,path)) {
                //表示通过
                return chain.filter(exchange);
            }

        }

        //获取请求头
        String token = request.getHeaders().getFirst("aaa");

        //如果token为空 未登录
        if(StrUtil.isBlank(token)){
            return error(exchange);
        }

        //验证token为空 是否合法
        try {
            Claims claims = jwtUtil.parseJwt(token);
        }catch (Exception e) {
            return error(exchange);
        }

        //表示通过
        return chain.filter(exchange);
    }

    //执行顺序
    @Override
    public int getOrder() {
        return 0;
    }

    /**
     * 拦截并返回自定义的json字符串
     */

    public Mono<Void> error(ServerWebExchange exchange){
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.OK);
        //这里在返回头添加编码，否则中文会乱码
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        byte[] bytes = JSONObject.toJSONBytes(Result.R(ResultEnum.TOKEN_INVALID), SerializerFeature.WriteMapNullValue);
        DataBuffer buffer = response.bufferFactory().wrap(bytes);
        return response.writeWith(Mono.just(buffer));
    }

}
